﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using formworks;
using System.Xml;
using System.Xml.Xsl;
using formworks.old;
using System.IO;

namespace codefactory
{
    public partial class FCodefactory : Form
    {

        private CodeEngine ce = null;
        private DB db = null;
        private string oldTitle = null;
        private DataSet tableInfo = null;

        private DataTable tables = null;

        public FCodefactory()
        {
            InitializeComponent();
        }

        private void FCodefactory_Load(object sender, EventArgs e)
        {
            oldTitle = this.Text;
            
            //
            ce = new CodeEngine();

           

            


            //for (int iter = 0; iter < dt.Rows.Count ; iter++)
            //{
            //    lbTableList.Items.Add(dt.Rows[iter][2]);
            //}
            
            
            
        }

        
        void makeit()
        {
            //
            DataSet tableDetail = new DataSet();
            //
            DataTable dtField = null;
            DataTable dtKeyList = null;

            string xmlString = null;

            string tableName = "";
            string description = "";
            //
            //遍历表名表，遍历生成代码
            for (int iter = 0; iter < tables.Rows.Count; iter++)
            {
                tableName = tables.Rows[iter][2].ToString();
                description = tables.Rows[iter][4].ToString();

                //获取表和表的键位关系
                dtField = db.getColumns(tableName );
                dtKeyList = db.getConstraints( tableName ).Tables[1];
                dtKeyList.TableName = "Key";

                //合并表
                ce.addCSharpDataType(dtField);
                ce.merageFieldsAndKeys(dtField, dtKeyList);
                tableDetail.Merge(dtField);

                //获取xml文档
                XmlDataDocument xmlDoc = ce.getXML(tableDetail,
                    tableName,
                    description);
                //获取文件名称，解析后的内容
                CodeEngine.FileEntity[] fileEntitys = 
                    ce.makeFile(tableName, xmlDoc);

                string[] path = new string[]
                {
                    tbEntity.Text,
                    tbImplement.Text,
                    tbInterface.Text,
                    tbHtml.Text
                };

                for (int iterFiles = 0; iterFiles < fileEntitys.Length; iterFiles++)
                {
                    
                    //entity
                    //implement
                    //interface
                    //html
                    using (FileStream fs = new FileStream(
                        System.AppDomain.CurrentDomain.BaseDirectory 
                        + path[iterFiles]
                        + "\\" + fileEntitys[iterFiles].fileName, FileMode.Create))
                    {
                        //using(StreamWriter sw = new StreamWriter(fs))
                        //{
                            fileEntitys[iterFiles].memoryStream.WriteTo(fs);
                            //sw.Flush();
                            //sw.Close();
                        //}
                        fs.Flush();
                        fs.Close();
                    }
                    
                }//end iterator file

                tableDetail.Clear();


            }//end tables rows count
        }//

        private void lbTableList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.lbTableList.SelectedItem != null)
            {

                DataRowView drv = (DataRowView)this.lbTableList.SelectedItem;
                //this.Name = drv[4].ToString();
                //
                DataTable dtField = db.getColumns(
                    drv[2].ToString());
                dgvField.DataSource = dtField;

                //
                //tableInfo.Merge(dtField);

                //
                DataSet dsKey = db.getConstraints(
                    drv[2].ToString());

                //
                DataTable dtKey = dsKey.Tables[0];
                for (int iter = 1; iter < dsKey.Tables.Count; iter++)
                {
                    dtKey.Merge(dsKey.Tables[iter]);
                }
                dgvKeyRelation.DataSource = dtKey;

                
                //
                //tableInfo.Merge(dtKeyList);


                //////////////////////////////////////////////////////////////////////////
                //合并表
                ce.addCSharpDataType(dtField);
                if (dsKey.Tables.Count > 1)
                {//只要制定列
                    DataTable dtKeyList = dsKey.Tables[1];
                    dtKeyList.TableName = "Key";
                    ce.merageFieldsAndKeys(dtField, dtKeyList);
                }
                
                tableInfo = new DataSet();
                tableInfo.Merge(dtField);

            }//end select item

        }//end method

        private void btnConnection_Click(object sender, EventArgs e)
        {
            string cstr = string.Format(@"server={0};uid={1};pwd={2};database={3}",
                new string[]
                {
                    this.tbAddress.Text,
                    this.tbUid.Text,
                    this.tbPwd.Text,
                    this.tbDataBaseName.Text
                });
            //连接数据库
            db = new DB(cstr);
            //初始化表的列表
            DataTable dt = db.getTables();
            DataView dv = new DataView();


            //读取出数据库中表的说明
            string sqlStr = "select sys.tables.name as TABLE_NAME, "
            + " sys.extended_properties.value as description "
            + " from sys.tables,sys.extended_properties where "
            + " sys.extended_properties.minor_id = sys.tables.parent_object_id "
            + " and sys.extended_properties.major_id = sys.tables.object_id";
            //
            DataSet ds = db.getDataSet(sqlStr);
            //add new col be descruption the table
            dt.Columns.Add("description");
            //
            DataTable descriptionDT = ds.Tables[0];
            for (int iter = 0; iter < descriptionDT.Rows.Count; iter++)
            {
                DataRow[] dr = dt.Select("TABLE_NAME='" + descriptionDT.Rows[iter]["TABLE_NAME"] + "'");
                dr[0]["description"] = descriptionDT.Rows[iter]["description"].ToString();
            }

            //
            dv.Table = dt;
            dv.Sort = "TABLE_NAME asc";
            dt = dv.Table;
            //
            lbTableList.DataSource = dv;
            lbTableList.DisplayMember = "TABLE_NAME";
            lbTableList.ValueMember = "description";
            //绑定dv
            dgvTable.DataSource = dv;

            //
            tables = dt;

            //
            //DataTable dtCols = db.getColumns("TB_ProductOutStock");
            //dgvField.DataSource = dtCols;

            this.Text = oldTitle + "--[连接到数据库完成！]";
        }

        private void btnMakeCode_Click(object sender, EventArgs e)
        {
            if (db == null)
            {
                MessageBox.Show("数据库未连接！");
                return;
            }

            DataRowView drv = (DataRowView)this.lbTableList.SelectedItem;

            //////////////////////////////////////////////////////////////////////////
            //
            string tableName = "";
            string description = "";
            tableName = drv[2].ToString();
            description = drv[4].ToString();


            //获取xml文档
            XmlDataDocument xmlDoc = ce.getXML(tableInfo,
                tableName,
                description);
            //获取文件名称，解析后的内容
            CodeEngine.FileEntity[] fileEntitys =
                ce.makeFile(tableName, xmlDoc);

            //string[] path = new string[]
            //    {
            //        tbEntity.Text,
            //        tbImplement.Text,
            //        tbInterface.Text,
            //        tbHtml.Text
            //    };



            rtbEntity.Text =
                System.Text.Encoding.UTF8.GetString(fileEntitys[0].memoryStream.ToArray());
            rtbImplement.Text =
                System.Text.Encoding.UTF8.GetString(fileEntitys[1].memoryStream.ToArray());
            rtbInterface.Text =
                System.Text.Encoding.UTF8.GetString(fileEntitys[2].memoryStream.ToArray());
            rtbHtml.Text =
                System.Text.Encoding.UTF8.GetString(fileEntitys[3].memoryStream.ToArray());

            //for (int iterFiles = 0; iterFiles < fileEntitys.Length; iterFiles++)
            //{


            //entity
            //implement
            //interface
            //html
            //---export---//
            //using (FileStream fs = new FileStream(
            //    System.AppDomain.CurrentDomain.BaseDirectory 
            //    + path[iterFiles]
            //    + "\\" + fileEntitys[iterFiles].fileName, FileMode.Create))
            //{
            //    //using(StreamWriter sw = new StreamWriter(fs))
            //    //{
            //        fileEntitys[iterFiles].memoryStream.WriteTo(fs);
            //        //sw.Flush();
            //        //sw.Close();
            //    //}
            //    fs.Flush();
            //    fs.Close();
            //}

            //}//end iterator file

            tableInfo.Clear();
            

            this.tabList.SelectedIndex = 3; //
            this.Text = oldTitle + "--[生成操作完成！]";
        }

        private void btnExportFile_Click(object sender, EventArgs e)
        {
            if (db == null)
            {
                MessageBox.Show("数据库未连接！");
                return;
            }
            
            makeit();
            MessageBox.Show("导出完成！");
            this.Text = oldTitle + "--[导出操作完成！]";
        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

    }//end class
}//end namespace
